import com.autumn.mybatis.metadata.EntityColumn;
import com.autumn.mybatis.metadata.EntityTable;
import com.autumn.mybatis.provider.DbProvider;
import com.autumn.mybatis.provider.mysql.MySqlProvider;

/**
 * <p>
 * </p>
 *
 * @description TODO
 * @author: 老码农
 * @create: 2020-04-03 11:42
 **/
public class AbstractScript {

    private DbProvider dbProvider = new MySqlProvider();

    public AbstractScript() {

    }

    protected DbProvider getDbProvider() {
        return this.dbProvider;
    }

    /**
     * 安全名称
     *
     * @param name
     * @return
     */
    protected String getSafeName(String name) {
        return name;
        //return getDbProvider().getSafeName(name);
    }

    /**
     * 打印连接主表Sql
     *
     * @param entityClass
     */
    public void printInnerMainTableSql(Class<?> entityClass) {
        printInnerMainTableSql(entityClass, false);
    }

    /**
     * 打印连接主表Sql
     *
     * @param entityClass
     */
    public void printInnerMainTableSql(Class<?> entityClass, boolean isAlias) {
        EntityTable table = EntityTable.getTable(entityClass);
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT ");
        int count = 1;
        for (EntityColumn col : table.getColumns()) {
            if (count > 1 && count <= table.getColumns().size()) {
                sb.append(",");
            }
            sb.append("a." + col.getColumnName());
            if (isAlias && !col.getPropertyName().equals(col.getColumnName())) {
                sb.append(" AS " + col.getPropertyName());
            }
            count++;
        }
        sb.append(" FROM " + table.getName() + " AS a");
        System.out.println(sb.toString());
    }

    /**
     * 打印表脚本
     *
     * @param entityClass
     */
    protected void printTableSql(Class<?> entityClass) {
        DbProvider provider = this.getDbProvider();
        String script = provider.getDefinitionBuilder().createTableScript(EntityTable.getTable(entityClass));
        System.out.println(script);
    }

    /**
     * 打印包脚本
     *
     * @param entityPackages 实体包路径
     */
    protected void printPackagesSql(String entityPackages) {
        DbProvider provider = this.getDbProvider();
        String script = provider.getDefinitionBuilder().createTableScripts(entityPackages);
        System.out.println(script);
    }
}
